/*
 * author      : 吴中勤 
 * date        : 2018/9/4
 * description : 将请求发送给moby, 并进行回调处理
 */

package com.deepexi.adapter.rest.sap;

import com.deepexi.adapter.common.exception.HttpNon200Exception;
import com.deepexi.adapter.common.sdk.RequestInfo;
import com.deepexi.adapter.log.Adapter2MobyRequestLog;
import com.deepexi.adapter.log.Adapter2SapRequestLog;
import com.deepexi.adapter.log.Log4Request;
import com.deepexi.adapter.log.LogRecorder;
import com.deepexi.adapter.sdk.moby.MobySdk;
import com.deepexi.adapter.sdk.sap.SapRecords;
import com.deepexi.adapter.sdk.sap.SapSdk;
import com.deepexi.adapter.sdk.sap.dto.callback.SapCallbackRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class CommonSapPushHandler {

    private static final Logger logger = LoggerFactory.getLogger(CommonSapPushHandler.class);

    @Autowired
    private MobySdk mobySdk;

    @Autowired
    private LogRecorder logRecorder;

    @Autowired
    private SapSdk sapSdk;

    /** 每次请求, 记录日志 */
    public String requestMobyAndSaveLog(RequestInfo requestInfo) throws IOException {
        String response = "";
        String errorStr = "";
        Long timeCost;
        IOException theEx = null;

        Long start = System.currentTimeMillis();
        try {
            // do http for string result
            response = mobySdk.doHttp(requestInfo);
        } catch (IOException ex) {
            errorStr = "moby接口:网络异常" + ex;
            theEx = ex;
        }
        timeCost = System.currentTimeMillis() - start;

        Log4Request log4Request = new Adapter2MobyRequestLog()
                .setReqId(requestInfo.reqId)
                .setUrl(requestInfo.url)
                .setRequest(requestInfo.strBody)
                .setApiType(requestInfo.apiType)
                .setErrorStr(errorStr)
                .setResponse(response)
                .setTimeCost(timeCost);
        logRecorder.record(log4Request);

        if (null != theEx) throw theEx;

        return response;
    }

    public String callbackToSap(List<String> keyNumList) {
        if (null == keyNumList || 0 == keyNumList.size()) {
            return null;
        }

        // 封装请求
        List<SapCallbackRequest> callbackRequestList = new ArrayList<>();
        keyNumList.forEach(keyNum -> {
            SapCallbackRequest callbackRequest = SapCallbackRequest.allOk(keyNum);
            callbackRequestList.add(callbackRequest);
        });
        RequestInfo requestInfo = sapSdk.requestInfo4Callback(new SapRecords<>(callbackRequestList));

        // 请求 & 日志记录
        String result = null;
        try {
            result = requestSapAndSaveLog(requestInfo);
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error("callback sap, response error", ex);
        }
        return result;
    }

    private String requestSapAndSaveLog(RequestInfo requestInfo) throws IOException, HttpNon200Exception {
        String response = "";
        String errorStr = "";
        Long timeCost;
        IOException theEx = null;

        Long start = System.currentTimeMillis();
        try {
            // do http for string result
            response = sapSdk.doHttp(requestInfo);
        } catch (IOException ex) {
            errorStr = "sap接口:网络异常" + ex;
            theEx = ex;
        }
        timeCost = System.currentTimeMillis() - start;

        Log4Request log4Request = new Adapter2SapRequestLog()
                .setReqId(requestInfo.reqId)
                .setUrl(requestInfo.url)
                .setRequest(requestInfo.strBody)
                .setApiType(requestInfo.apiType)
                .setErrorStr(errorStr)
                .setResponse(response)
                .setTimeCost(timeCost);
        logRecorder.record(log4Request);

        if (null != theEx) throw theEx;

        return response;
    }
}
